package org.example.rejectmsg;

import com.rabbitmq.client.*;
import org.example.exchange.direct.DirectProducer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/06/22/16:53
 * @Description:普通的消费者
 */
public class RejectRequeuConsumer {

    public static void main(String[] argv)
            throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");

        // 打开连接和创建信道
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        // 定义交换器
        channel.exchangeDeclare(RejectProducer.EXCHANGE_NAME,"direct");

        /*声明一个队列*/
        String queueName = RejectProducer.QUEUE_NAME;
        channel.queueDeclare(queueName,false,false,
                false,null);

        /*绑定，将队列和交换器通过路由键进行绑定*/
        String routekey = "error";
        channel.queueBind(queueName,RejectProducer.EXCHANGE_NAME,routekey);

        System.out.println("waiting for message........");
        /*声明了一个消费者*/
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                try{
                    String message = new String(body, "UTF-8");
                    System.out.println("Received["
                            +envelope.getRoutingKey()
                            +"]"+message);
                    throw new RuntimeException("处理异常"+message);
                }catch (Exception e){
                    e.printStackTrace();
                    channel.basicReject(envelope.getDeliveryTag(),false);
                }
            }
        };
        /*消费者正式开始在指定队列上消费消息*/
        channel.basicConsume(queueName,false,consumer);
    }
}
